package actionForm;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.springframework.context.ApplicationContext;

import util.DomainUtils;
import domain.dao.interfaces.IDAOUser;
import domain.entities.interfaces.IUser;

public class LoginValidationForm extends ActionForm {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	String login = null;
	String password = null;

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = DomainUtils.trim(login);
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void reset(ActionMapping mapping, HttpServletRequest request) {
		this.login = null;
		this.password = null;
	}

	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();

		ApplicationContext context = util.SpringUtils.getApplicationContext();

		IDAOUser daoUser = (IDAOUser) context.getBean("beanDAOUser");
		List<IUser> users = daoUser.getAll();


		HttpSession session = request.getSession(false);
		IUser foundUser = null;

		// Checking session
		if (session == null || users == null) {
			errors.add(DomainUtils.ALERT_ERROR_STRING, new ActionMessage(
					"session.error"));
			
			DomainUtils.keepParametersContent(request);
			
			return errors;
		}

		if (session.getAttribute(DomainUtils.CURRENT_USER_STRING) != null) {
			errors.add(DomainUtils.ALERT_ERROR_STRING, new ActionMessage(
					"login.session.error"));
			
			DomainUtils.keepParametersContent(request);
			
			return errors;
		}

		// Checking login
		foundUser = daoUser.getByLogin(login);
		

		if (foundUser == null) {
			errors.add("login", new ActionMessage("login.login.error"));
			
			DomainUtils.keepParametersContent(request);
			
			return errors;
		}

		// Checking password
		if (foundUser.getPassword().compareTo(password) != 0) {
			errors.add("password", new ActionMessage("login.login.error"));
			
			DomainUtils.keepParametersContent(request);
			
			return errors;
		}
		return errors;
	}

}
